#include <string.h>
#include "gtktester_search.h"

GtkWidget *gtktester_find_widget_by_name (const gchar *name)
{
	GtkWidget *result = NULL;
	GList *window_list = gdk_window_get_toplevels(), *ptr;
	if (name)
		for (ptr = window_list; ptr != NULL && result == NULL; ptr = ptr->next) {
			result = gtktester_find_widget_in_window_by_name (GDK_WINDOW(ptr->data), name);
		}
	g_list_free (window_list);
	return result;
}

GtkWidget *gtktester_find_widget_in_window_by_name (GdkWindow *window, const gchar *name)
{
	gpointer widget_ptr;
	GtkWidget *widget, *result = NULL;
	gdk_window_get_user_data (window, &widget_ptr);
	if (widget_ptr != 0) {
		widget = GTK_WIDGET(widget_ptr);
		/*printf("In gtktester_search_widget: %x, %d, %s\n", window, gdk_window_get_window_type (window), gtk_window_get_title(GTK_WINDOW(widget)));*/
		result = gtktester_find_widget_in_widget_by_name (widget, name);
	}
	return result;
}

GtkWidget *gtktester_find_widget_in_widget_by_name (GtkWidget *widget, const gchar *name)
{
	const gchar *this_widgets_name = gtk_widget_get_name (widget);
	GtkWidget *result = NULL;
	GList *children, *ptr;

	if (!strcmp(name, this_widgets_name))
		result = widget;
	else if (GTK_IS_CONTAINER (widget)) {
		children = gtk_container_get_children (GTK_CONTAINER (widget));
		ptr = children;
		while (ptr != NULL && result == NULL) {
			result = gtktester_find_widget_in_widget_by_name (GTK_WIDGET(ptr->data), name);
			ptr = ptr->next;
		}
	}
	return result;
}
